/**
 * 
 * EXERCISE 1
 * 
 * @param {Promise} promise 
 * @param {function} asyncTransformer 
 */
function flatMapPromise(promise, asyncTransformer){
  return new Promise((resolve, reject) => {
    // promise
    //   .then(res => {
    //       asyncTransformer(res).then(result => {
    //         resolve(result);
    //       })
    //     });
    promise.then(asyncTransformer).then(resolve).catch(reject);
  });
}

/**
 * 
 * EXERCISE 2
 * 
 * @param {Promise} firstPromise 
 * @param {function} slowAsyncProcess 
 */
function chainTwoAsyncProcesses(firstPromise, slowAsyncProcess){
  return firstPromise
          .then(slowAsyncProcess)
          // .then(Promise.resolve) // TypeError: PromiseResolve called on non-object
          // .then(res => Promise.resolve(res));
}

/**
 * 
 * EXERCISE 3
 * 
 * @param {function} getUserById 
 * @param {function} getOrganizationById 
 */
function makeGetUserByIdWithOrganization(getUserById, getOrganizationById){
  return function getUserByIdWithOrganization(userId){
    return getUserById(userId)
            .then(userInfo => {
              return new Promise((resolve, reject) => {
                if (userInfo) {
                  const id = userInfo['organizationId'];
                  getOrganizationById(id).then(res => {
                    resolve({...userInfo, organization: res});
                  });
                } else {
                  resolve(undefined);
                }
              })
            });
  };
}

module.exports = {
  flatMapPromise,
  chainTwoAsyncProcesses,
  makeGetUserByIdWithOrganization,
};